const {User, Blog, Access} = require('../models')
const dateUtils = require('../lib/date')

module.exports = function (router) {
  // 根据用户名获取博客信息
  router.get('/c/user/:username/blog', function * () {
    this.checkParams('username').notEmpty('缺少用户名。')
    if (this.errors) this.throwError()

    let {username} = this.params
    let user = yield User.findByUsername(username).exec()
    if (!user) this.throw('用户不存在。', 404)
    let blog = yield Blog.findOne({owner: user._id}).exec()
    if (!blog) this.throw('该用户尚未开通博客。', 404)
    if (!blog.enable) this.throw('该博客暂时关闭。')

    // 访问统计
    let ip = this.ip
    let visitor = this.state && this.state.user ? this.state.user._id : null
    let access = yield Access.findOne({ip, accessedAt: {$gte: dateUtils.today(), $lt: dateUtils.tomorrow()}})
    if (!access) yield Access.create({ip, visitor, blog})
    else if (!access.visitor && visitor) yield access.update({$set: {visitor}})

    this.body = this.apiSuccess({blog})
  })

  // 根据博客id获取博客信息
  router.get('/c/blog/:blogId', function * () {
    this.checkParams('blogId').notEmpty('缺少id')
    if (this.errors) this.throwError()

    let {blogId} = this.params
    let blog = yield Blog.findById(blogId).exec()
    if (!blog) this.throw('博客不存在', 404)
    if (!blog.enable) this.throw('该博客暂时关闭。')

    this.body = this.apiSuccess({blog})
  })

  // 获取个人博客信息
  router.get('/blog', function * () {
    let {_id} = this.state.user
    let blog = yield Blog.findOne({owner: _id}).exec()
    if (!blog) this.throw('你尚未开通博客。')

    this.body = this.apiSuccess({blog})
  })

  // 开通博客
  router.post('/blog', function * () {
    this.checkBody('name').notEmpty('请输入博客名称。').trim()
    if (this.errors) this.throwError()

    let {name, desc} = this.request.body
    let {_id: owner} = this.state.user
    let blog = yield Blog.findOne({owner}).exec()
    if (blog) this.throw('你已开通博客。')

    blog = yield Blog.create({name, desc, owner})
    yield User.findByIdAndUpdate(owner, {$set: {blog}})
    this.body = this.apiSuccess({blog})
  })

  // 开启博客或关闭博客
  router.put('/blog/:blogId', function * () {
    this.checkBody('enable').notEmpty('缺少enable')
    this.checkParams('blogId').notEmpty('缺少id')
    if (this.errors) this.throwError()

    let {enable} = this.request.body
    let {blogId} = this.params
    let blog = yield Blog.findById(blogId).exec()
    if (!blog) this.throw('博客不存在。')
    if (enable === true || enable === false) {
      yield blog.update({$set: {enable}})
    } else {
      enable = null
    }

    this.body = this.apiSuccess({enable})
  })
}
